package cn.tedu.oa_system.security;

import cn.tedu.oa_system.mapper.UserMapper;
import cn.tedu.oa_system.pojo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author MW
 * @Description
 * @CreateDate 2023/2/28
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("根据用户名({})查找管理员信息.....",s);
        UserInfo user = userMapper.getUserInfoByUsername(s);
        log.debug("查找到的用户信息为:{}",user);
        if (user == null){
            log.error("登录失败,用户不存在");
            throw new BadCredentialsException("===用户名不存在===");
        }

        UserDetails userDetails = User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .accountExpired(false)
                .accountLocked(false)
                .disabled(false)
                .credentialsExpired(false)
                .authorities(user.getPermissions().toArray(new String[] {}))
                .build();
        log.debug("将向Spring Security返回尝试登录的用户信息: {}",userDetails);
        return userDetails;
    }
}
